package com.bd.lrb_q.controller;

import com.bd.lrb_q.entity.Product;
import com.bd.lrb_q.mapper.ProductMapping;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;

@RestController
public class ProductController {

    @Autowired(required = false)
    ProductMapping mapper;

    @Value("d:/upload")
    private String dirPath;

    @RequestMapping("/product/insert")
    public void productInsert(Product product, MultipartFile file) throws IOException {
        String fileName = file.getOriginalFilename();//得到文件名
        String suffix = fileName.substring(fileName.lastIndexOf("."));//后缀
        fileName = UUID.randomUUID() + suffix;//唯一文件名

        SimpleDateFormat format = new SimpleDateFormat("/yyy/MM/dd/");//得到日期路径
        Date date = new Date();//得到时间对象
        String datePath = format.format(date);//自定义格式

        File dirFile = new File(dirPath + datePath);//文件
        if (!dirFile.exists()) {
            dirFile.mkdirs();
        }
        String filePath = dirPath + datePath + fileName;//完整文件路径
        file.transferTo(new File(filePath));//保存文件
        product.setUrl(datePath+fileName);//把图片给到作品对象
        mapper.insert(product);
    }

}
